package com.ebuy.shopping.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ebuy.shopping.common.utils.Contants;
import com.ebuy.shopping.common.utils.CoverUtils;
import com.ebuy.shopping.model.Category;
import com.ebuy.shopping.model.News;
import com.ebuy.shopping.model.Notice;
import com.ebuy.shopping.model.Order;
import com.ebuy.shopping.model.Product;
import com.ebuy.shopping.model.Shop;
import com.ebuy.shopping.model.User;
import com.ebuy.shopping.service.ICategoryService;
import com.ebuy.shopping.service.INewsService;
import com.ebuy.shopping.service.INoticeService;
import com.ebuy.shopping.service.IOrderService;
import com.ebuy.shopping.service.IProductService;
import com.ebuy.shopping.service.IShopService;
import com.ebuy.shopping.service.IUserService;

/**
 * 
 * @ClassName: MainController
 * @Description: 主页
 * @author 郭文峰
 * @date 2017年8月14日 下午12:58:11
 * 
 */
@Controller
@RequestMapping("/main")
public class MainController
{
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IProductService productService;

    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String login(Model model) throws Exception
    {
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        return "main/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    private String login(String userName, String name, String password,
            String address, HttpSession session, Model model) throws Exception
    {

        User user = new User();
        user.setUserId(userName);
        user.setUserName(name);
        user.setAddress(address);
        user.setSex("男");
        user.setStatus(1);
        user.setPassword(password);
        int flag = userService.add(user);
        if (flag > 0)
        {
            System.out.println("注册成功");
            session.setAttribute("user", user);
        }
        else
        {
            return "forward:/main/register";
        }
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        // 今日特价
        List<Product> recommendProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_RECOMMEND);
        model.addAttribute("recommendProducts", recommendProducts);
        // 热卖产品
        List<Product> hotProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_HOT);
        model.addAttribute("hotProducts", hotProducts);
        // 最新公告
        List<Notice> notices = noticeService.getNotices();
        model.addAttribute("notices", notices);
        // 新闻动态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", "create_time");
        map.put("sort", "asc");
        map.put("offset", 0);
        map.put("pageSize", 7);
        List<News> news = newsService.getNewsPage(map);
        model.addAttribute("news", news);
        if ("admin".equals(userName))
        {
            return "manage/index";
        }
        return "main/index";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String indexList(Model model) throws Exception
    {
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        // 今日特价
        List<Product> recommendProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_RECOMMEND);
        model.addAttribute("recommendProducts", recommendProducts);
        // 热卖产品
        List<Product> hotProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_HOT);
        model.addAttribute("hotProducts", hotProducts);
        // 最新公告
        List<Notice> notices = noticeService.getNotices();
        model.addAttribute("notices", notices);
        // 新闻动态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", "create_time");
        map.put("sort", "asc");
        map.put("offset", 0);
        map.put("pageSize", 7);
        List<News> news = newsService.getNewsPage(map);
        model.addAttribute("news", news);

        return "main/index";
    }

    @RequestMapping(value = "/cancel", method = RequestMethod.GET)
    public String cancel(HttpSession session, Model model) throws Exception
    {
        User user = (User) session.getAttribute("user");
        if (user != null)
        {
            session.removeAttribute("user");
        }

        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        // 今日特价
        List<Product> recommendProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_RECOMMEND);
        model.addAttribute("recommendProducts", recommendProducts);
        // 热卖产品
        List<Product> hotProducts = productService
                .getProductsBySaleType(Contants.SALE_TYPE_HOT);
        model.addAttribute("hotProducts", hotProducts);
        // 最新公告
        List<Notice> notices = noticeService.getNotices();
        model.addAttribute("notices", notices);
        // 新闻动态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order", "create_time");
        map.put("sort", "asc");
        map.put("offset", 0);
        map.put("pageSize", 7);
        List<News> news = newsService.getNewsPage(map);
        model.addAttribute("news", news);
        return "main/index";
    }

    @RequestMapping(value = "{id}/product", method = RequestMethod.GET)
    public String productList(@PathVariable
    int id, Model model) throws Exception
    {
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        // 产品列表
        List<Product> products = productService.getProductsByCategoryId(id);
        model.addAttribute("products", products);

        return "main/product_list";
    }

    @RequestMapping(value = "/shop", method = RequestMethod.GET)
    public String list(Model model, HttpSession session) throws Exception
    {
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        User user = (User) session.getAttribute("user");
        if (user != null)
        {
            System.out.println("user.getUserId():" + user.getUserId());
        }
        else
        {
            return "forward:/login";
        }

        List<Shop> shops = shopService.getShopsByUser(user.getUserId());
        model.addAttribute("shops", shops);

        return "main/shopping";
    }

    @RequestMapping(value = "/shop", method = RequestMethod.POST)
    public String shop(@RequestBody
    String shopsJsonStr, HttpSession session, Model model) throws Exception
    {
        User user = (User) session.getAttribute("user");
        if (user != null)
        {
            System.out.println("user.getUserId():" + user.getUserId());
        }
        else
        {
            return "forward:/login";
        }
        String[] shops = CoverUtils.coverShopRequest(shopsJsonStr);
        for (int i = 0; i < shops.length; i++)
        {
            Shop shop = shopService.load(Integer.valueOf(shops[i]));

            int qu = shop.getEodQuantity();

            int cos = shop.getEpPrice();

            int cost = qu * cos;

            Order order = new Order();

            order.setCost(Double.valueOf(cost));

            order.setUserId(user.getUserId());
            order.setUserName(user.getUserName());
            order.setUserAddress(user.getAddress());
            order.setStatus(1);
            order.setType(1);
            order.setCreateTime(new Date());

            orderService.add(order);
            shop.setValid(0);
            shopService.update(shop);

        }

        System.out.println("参数：" + shopsJsonStr);

        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        return "main/shopping_result";
    }

    @RequestMapping(value = "{id}/goshop", method = RequestMethod.GET)
    public String goShop(@PathVariable
    int id, HttpSession session, Model model) throws Exception
    {
        User user = (User) session.getAttribute("user");
        if (user != null)
        {
            System.out.println("user.getUserId():" + user.getUserId());
        }
        else
        {
            return "forward:/login";
        }
        // 添加到购物车
        Product pro = productService.load(id);
        Shop shop = new Shop();
        shop.setEodQuantity(1);
        shop.setEpFileName(pro.getFileName());
        shop.setEpName(pro.getEpName());
        shop.setEpPrice((new Double(pro.getPrice())).intValue());
        shop.setEuUserId(user.getUserId());
        shop.setValid(1);
        shopService.add(shop);

        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);

        List<Shop> shops = shopService.getShopsByUser(user.getUserId());
        model.addAttribute("shops", shops);

        return "main/shopping";
    }

    // 前台公告详细展示

    @RequestMapping(value = "/noticeView", method = RequestMethod.GET)
    public String noticeView(int id, Model model)
    {
        Notice notice = noticeService.load(id);
        model.addAttribute("notice", notice);
        return "main/noticeView";
    }

    // 前台新闻详细展示

    @RequestMapping(value = "/newsView", method = RequestMethod.GET)
    public String newsView(int id, Model model) throws Exception
    {
        News news = newsService.load(id);
        System.out.println(news);
        model.addAttribute("news", news);

        return "main/newsView";
    }

    @RequestMapping(value = "/product/{id}/show", method = RequestMethod.GET)
    private String show(@PathVariable
    int id, Model model) throws Exception
    {
        // 栏目显示
        List<Category> categoriesIndex = categoryService.getCategoriesByIndex();
        model.addAttribute("categoriesIndex", categoriesIndex);
        List<Category> categoriesSeconde = categoryService
                .getCategoriesBySecondIndex();
        model.addAttribute("categoriesSeconde", categoriesSeconde);
        // 导航
        Map<String, List<Category>> navigationMap = new HashMap<String, List<Category>>();
        for (Category category : categoriesIndex)
        {
            int catId = category.getId();
            String catName = category.getName();
            List<Category> secondCat = categoryService
                    .getCategoriesByParentId(catId);
            if (secondCat != null)
            {
                navigationMap.put(catName, secondCat);
            }

        }
        model.addAttribute("navigationMap", navigationMap);
        Product product = productService.load(id);
        model.addAttribute(product);
        return "main/product_show";

    }

}
